import { BASE_URL, TIMEOUT } from './config';
import localCache from '@/utils/cache';
import axios from 'axios';
const http = axios.create({
  baseURL: BASE_URL,
  timeout: TIMEOUT,
});
//请求拦截器
http.interceptors.request.use(
  (config) => {
    //获取登录后的token加到请求头
    //按照接口文档的形式
    const token = localCache.getCache('token');
    if (token) {
      //在请求头中添加token
      config.headers.token = token;
    }
    return config;
  },
  (err) => {}
);

//响应拦截器
http.interceptors.response.use(
  (res) => {
    // console.log('响应成功的拦截', res);
    //看后端返回的数据解构是怎么样
    return res.data;
  },
  (error) => {
    // console.log('响应失败的拦截', err);
    //想要失败被捕获，手动来一个Promise.reject
    return Promise.reject(
      (function (resp) {
        console.group(
          `%c【代码${resp.status}: ${resp.data.msg}】`,
          'color:blue;font-size:15px;'
        );
        let inputdata = resp.config.data
          ? JSON.parse(resp.config.data)
          : undefined;
        let inputparams = resp.config.params ? resp.config.params : undefined;
        console.log(
          `%cPREVIEW:\n`,
          'color:green;font-weight:bold;font-size:18px',
          `Data:`,
          inputdata,
          `\n`,
          `Params:`,
          inputparams,
          `\n`,
          { Method: resp.config.method },
          `\n`,
          { Url: resp.config.url },
          `\n`,
          { Envir: process.env.NODE_ENV },
          `\n`,
          { Type: resp.config.headers['Content-Type'] },
          `\n`,
          { msg: resp.data.msg },
          `\n`,
          { status: resp.status },
          `\n`
        );
        console.groupEnd();
      })(error.response)
    );
  }
);

export default http;
